﻿using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using net.xBei.Models;
using net.xBei.Models.json;
using net.xBei.WebApi.Helper;
using net.xBei.WebApi.Repository;

namespace net.xBei.WebApi.Controller {
    /// <summary>
    /// 基础控制器
    /// </summary>
    /// <remarks>
    /// 初始化，不需要检查用户权限
    /// </remarks>
    /// <param name="logger"></param>
    public abstract class BaseController(ILogger<BaseController> logger) : ControllerBase {
        /// <summary>
        /// 用户Ip地址
        /// </summary>
        protected string IpAddress => Request.HttpContext.Connection.RemoteIpAddress?.ToString() ?? string.Empty;
        /// <summary>
        /// 日志
        /// </summary>
        protected ILogger Logger { get; } = logger;
        /// <summary>
        /// 
        /// </summary>
        public IAuthorizationRepository? AuthorizationRepository { get; }

        /// <summary>
        /// 初始化，需要检查用户权限
        /// </summary>
        /// <param name="authorizationRepository"></param>
        /// <param name="logger"></param>
        protected BaseController(IAuthorizationRepository authorizationRepository, ILogger<BaseController> logger) : this(logger) {
            AuthorizationRepository = authorizationRepository;
        }

        /// <summary>
        /// 当前用户ID，未登录返回-1
        /// </summary>
        protected virtual int UserId {
            get {
#if DEBUG
                var id = HttpContext.GetCurrentUserId();
                //return id > 0 ? id : 52;
                return id > 0 ? id : 1;
#else
                return HttpContext.GetCurrentUserId();
#endif
            }
        }

        #region 用户权限
        /// <summary>
        /// 是否系统用户（API之间调用）
        /// </summary>
        protected bool IsSystemUser => HttpContext.User.Identity?.Name == CommonConsts.SystemUserId;
        /// <summary>
        /// 是否系统用户（API之间调用）
        /// </summary>
        /// <returns></returns>
        protected async Task<bool> IsSystemUserAsync() {
#if !DEBUG
            if (HttpContext.User.Identity?.Name != CommonConsts.SystemUserId) {
                return false;//Forbid();
            }
#endif
            return await Task.FromResult(true);
        }
        /// <summary>
        /// 检查用户权限
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="controller"></param>
        /// <param name="action"></param>
        /// <param name="permissionKey"></param>
        /// <returns></returns>
        protected async Task<bool> CheckUserPermissionAsync(int userId, string controller, string action, string permissionKey = "A") {
            return AuthorizationRepository == null
                ? throw new NullReferenceException("未初始化AuthorizationRepository")
                : await AuthorizationRepository.CheckUserPermissionAsync(userId, controller, action, permissionKey);
        }
        #region IsBackUser
        /// <summary>
        /// 判断是否后台用户
        /// </summary>
        /// <returns></returns>
        protected async Task<bool> IsBackUserAsync() {
            return AuthorizationRepository == null
                ? throw new NullReferenceException("未初始化AuthorizationRepository")
                : await AuthorizationRepository.IsBackUserAsync(UserId);
        }
        /// <summary>
        /// 判断是否后台用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        protected async Task<bool> IsBackUserAsync(int userId) {
            return AuthorizationRepository == null
                ? throw new NullReferenceException("未初始化AuthorizationRepository")
                : await AuthorizationRepository.IsBackUserAsync(userId);
        }

        #endregion
        #region IsAdmin
        /// <summary>
        /// 判断是否后台管理员
        /// </summary>
        /// <returns></returns>
        protected async Task<bool> IsAdminAsync() {
            return AuthorizationRepository == null
                ? throw new NullReferenceException("未初始化AuthorizationRepository")
                : await AuthorizationRepository.IsAdminAsync(UserId);
        }
        /// <summary>
        /// 判断是否后台管理员
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        protected async Task<bool> IsAdminAsync(int userId) {
            return AuthorizationRepository == null
                ? throw new NullReferenceException("未初始化AuthorizationRepository")
                : await AuthorizationRepository.IsAdminAsync(userId);
        }
        #endregion
        #endregion

        #region 快捷输出
        /// <summary>
        /// 返回一个代表成功的简单数据包
        /// </summary>
        /// <returns></returns>
        protected IActionResult Success() => Ok(new { success = true });
        /// <summary>
        /// 标准返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="result"></param>
        /// <returns></returns>
        protected IActionResult Success<T>(T result) {
            if (null == result) {
                return StatusCode((int)HttpStatusCode.InternalServerError, new { Success = false, Message = "服务错误" });
            }
            return Ok(new { success = true, data = result, });
        }
        /// <summary>
        /// 参数错误
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="paramName"></param>
        /// <param name="rawValue"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        protected IActionResult BadRequest<T>(string paramName, T rawValue, string errorMessage) {
            return BadRequest(new ResponseData<object> {
                Success = false,
                Code = 400,
                Message = "输入参数错误",
                Data = new[]{ new {
                    param = paramName,
                    rawValue ,
                    errorMessage
                } }
            });
        }
        /// <summary>
        /// 错误返回
        /// </summary>
        /// <param name="responseData"></param>
        /// <returns></returns>
        protected IActionResult Error<T>(ResponseData<T> responseData) {
            return Ok(new {
                Success = false,
                responseData.Message,
                responseData.Code,
            });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="responseData"></param>
        /// <returns></returns>
        protected IActionResult Error(ResponseData responseData) {
            return Ok(new {
                Success = false,
                responseData.Message,
                responseData.Code,
            });
        }
        /// <summary>
        /// 错误返回
        /// </summary>
        /// <param name="message"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        protected IActionResult Error(string message, int code = -1) {
            return Ok(new {
                Success = false,
                Message = message,
                Code = code,
            });
        }
        /// <summary>
        /// 为实现
        /// </summary>
        /// <returns></returns>
        protected async Task<IActionResult> NotImplementedAsync()
            => await ErrorAsync("未实现", 404);
        /// <summary>
        /// 错误返回
        /// </summary>
        /// <param name="message"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        protected async Task<IActionResult> ErrorAsync(string message, int code = -1) {
            await Task.Delay(0);
            return Ok(new {
                Success = false,
                Message = message,
                Code = code,
            });
        }

        #endregion
    }//end class
}
